<template>
  <div>
    <el-drawer v-loading="fasonRecaver" element-loading-text="正在发送邀请 请稍后" title="批量邀约" :visible="isDrawer"
      :direction="direction" :before-close="handleClose" size="50%">
      <div class="pa-10 overflow-y-auto">
        <div class="px-50">
          <el-steps :active="stepsVal" simple>
            <el-step title="筛选邀约达人" :status="stepsVal > 1 ? 'success' : 'process'"></el-step>
            <el-step title="填写邀约信息" :status="stepsVal == 2 ? 'process' : stepsVal > 2 ? 'success' : 'wait'
              "></el-step>
            <el-step title="邀约发送完成" :status="stepsVal == 3 ? 'success' : 'wait'"></el-step>
          </el-steps>
        </div>

        <template v-if="stepsVal == 1">
          <div class="f-between-center font-size-16 mt-20 mb-20">
            <div>
              <span> 待邀约列表 </span>
              <span class="font-size-12" style="color: #909399">
                ({{ accordData.length }}位达人)
              </span>
            </div>
            <div v-if="!accordData.length == 0" class="flex f--center">
              <el-button type="primary" size="small" icon="el-icon-remove-outline" @click="cancelAllInvitation">
                取消邀约
              </el-button>
              <el-tooltip class="item" effect="dark" content="点击按钮选择需要取消邀约的达人，再次点击按钮即可取消该批达人的邀约。" placement="top-end">
                <img class="ml-10" src="@/assets/images/question-mark.png" style="width: 15px; height: 15px" alt="" />
              </el-tooltip>
            </div>
          </div>
          <div v-if="accordData.length > 0" class="overflow-y-auto table-box position-re" ref="box"
            style="max-height: 800px">
            <div class="prompt" v-if="isTips">
              <div class="f--center">
                <img class="table-box-prompt-img" src="@/assets/images/down.png" alt="" />
                <div>向下滑动，查看更多达人信息</div>
                <span style="top: 5px; right: 2px" class="position-ab cursor-pointer">
                  <img src="@/assets/images/close.png" alt="" style="width: 20px; height: 20px"
                    @click="isTips = false" />
                </span>
              </div>
            </div>
            <div v-for="(item, index) in accordDatauteyr" :key="index"
              style="border-bottom: 0.5px solid rgb(192, 196, 204, 0.4)" class="flex mb-10 pb-10 px-30">
              <div class="f--3 flex f-start-center">
                <span class="font-color-3"> {{ index + 1 }} </span>
                <el-tooltip class="item" effect="dark" content="点击前往达人主页" placement="top">
                  <img :src="item.author_base.avatar" alt="" class="img-style ml-20 cursor-pointer"
                    @click="jumpHomepage(item.author_base)" />
                </el-tooltip>
                <div class="ml-10">
                  <div class="font-size-14 font-color-1">
                    <span> {{ item.author_base.nickname }} </span>
                    <span> LV{{ item.author_base.author_level }} </span>
                  </div>
                  <div class="font-size-12 font-color-3 mt-5">
                    <span v-if="item.author_tag.main_cate.length > 0">
                      {{ item.author_tag.main_cate.join("/") }}
                    </span>
                    <span class="ml-10">
                      {{ item.author_base.city }}
                    </span>
                  </div>
                  <div class="mt-5 mb-10">
                    <span class="font-size-12 primary-tag mr-5">{{
                      item.author_tag.high_response_rate
                      }}</span>
                    <template v-if="item.author_tag.work_cate">
                      <span class="tag font-size-12" v-for="(item, index) in item.author_tag.work_cate" :key="index">
                        {{ item }}
                      </span>
                    </template>
                  </div>
                </div>
              </div>
              <div class="f--1 font-size-12 text-align-center f--center">
                <div>
                  <div>粉丝数</div>
                  <div class="mt-10 font-color-3">
                    {{ commonNumFilter(item.fans_num) }}
                  </div>
                </div>
              </div>
              <div class="f--1 font-size-12 text-align-center f--center">
                <div>
                  <div>销售总额</div>
                  <div class="mt-10 font-color-3">
                    {{
                      stateReturnVal(item.sale_info.total_sales.sale_status, [
                        commonNumFilter(item.sale_info.total_sales.sale_low),
                        commonNumFilter(item.sale_info.total_sales.sale_high),
                      ])
                    }}
                  </div>
                </div>
              </div>

              <div class="f--1 font-size-12 font-size-12 text-align-center f--center">
                <div>
                  <div>直播销售总额</div>
                  <div class="mt-10 font-color-3">
                    {{
                      stateReturnVal(
                        item.sale_info.live_total_sales.sale_status,
                        [
                          commonNumFilter(
                            item.sale_info.live_total_sales.sale_low
                          ),
                          commonNumFilter(
                            item.sale_info.live_total_sales.sale_high
                          ),
                        ]
                      )
                    }}
                  </div>
                </div>
              </div>

              <div class="f--1 font-size-12 font-size-12 text-align-center f--center">
                <div>
                  <div>视频销售总额</div>
                  <div class="mt-10 font-color-3">
                    {{
                      stateReturnVal(
                        item.sale_info.video_total_sales.sale_status,
                        [
                          commonNumFilter(
                            item.sale_info.video_total_sales.sale_low
                          ),
                          commonNumFilter(
                            item.sale_info.video_total_sales.sale_high
                          ),
                        ]
                      )
                    }}
                  </div>
                </div>
              </div>
              <div class="f--1 font-size-12 font-size-12 text-align-center f--center">
                <div>
                  <div>图文销售总额</div>
                  <div class="mt-10 font-color-3">
                    {{
                      stateReturnVal(
                        item.sale_info.image_text_total_sales.sale_status,
                        [
                          commonNumFilter(
                            item.sale_info.image_text_total_sales.sale_low
                          ),
                          commonNumFilter(
                            item.sale_info.image_text_total_sales.sale_high
                          ),
                        ]
                      )
                    }}
                  </div>
                </div>
              </div>
              <div class="f--1 font-size-12 font-size-12 text-align-center f--center">
                <div>
                  <div>橱窗销售总额</div>
                  <div class="mt-10">
                    {{
                      stateReturnVal(
                        item.sale_info.window_total_sales.sale_status,
                        [
                          commonNumFilter(
                            item.sale_info.window_total_sales.sale_low
                          ),
                          commonNumFilter(
                            item.sale_info.window_total_sales.sale_high
                          ),
                        ]
                      )
                    }}
                  </div>
                </div>
              </div>
              <div class="f--1 f--center">
                <el-button size="small" type="text" @click="cancelInvitation(item)">
                  取消邀约
                </el-button>
              </div>
              <div class="f--1 f--center" v-if="isMultipleChoice">
                <el-checkbox :label="item.author_base.uid" v-model="checkList" v-if="isMultipleChoice">{{ ""
                }}</el-checkbox>
              </div>
            </div>
          </div>
          <div class="flex f--center mt-20">
            <el-pagination @current-change="handleCurrentChange" :current-page="pageObj.currentPage"
              :page-size="pageObj.pageSize" background layout="prev, pager, next,jumper" :total="accordData.length">
            </el-pagination>
          </div>

          <div class="f--center mt-20">
            <el-button type="primary" @click="stepsVal = 2" icon="el-icon-right" v-if="accordData.length > 0">
              下一步
            </el-button>
          </div>
          <div class="px-20 flex f--center font-size-14" v-if="accordData.length == 0">
            暂无满足条件的达人，请关闭弹窗重新邀约。<el-button type="text" class="ml-10" @click="$emit('update:isDrawer', false)">
              关闭弹窗
            </el-button>
          </div>
        </template>
        <template v-if="stepsVal == 2">
          <div class="flex">
            <div class="f--2">
              <div class="font-size-14 flex f-between-center mt-30">
                <span class="font-size-16"> 邀约信息填写 </span>
                <el-button type="text" class="mr-20" @click="stepsVal = 1">
                  返回上一步
                  <i class="el-icon-back"> </i>
                </el-button>
              </div>
              <el-alert show-icon title="提示" type="warning">
                首次发起邀约带货需按照模板填写信息，达人回复后才可继续发送。<span class="cursor-pointer" @click="
                  jumpPage(
                    'https://school.jinritemai.com/doudian/web/lark-doc/fdHzuiNoZkj1K?from=shop_buyin_banner'
                  )
                  ">
                  查看详情
                </span>
              </el-alert>
              <el-card class="mt-10">
                <div class="flex">
                  <div><span class="required"> * </span> 邀约信息</div>
                  <el-input class="f--1 ml-10" type="textarea" rows="5" resize="none" maxlength="150" show-word-limit
                    v-model="contact_info.content"></el-input>
                </div>
                <div class="flex mt-20">
                  <span class="mr-20 ml-10 font-size-14"> 专属权益 </span>
                  <el-checkbox-group v-model="rights">
                    <el-checkbox label="1">可聊高佣</el-checkbox>
                    <el-checkbox label="2">免费申样</el-checkbox>
                    <el-checkbox label="4">视频素材支持</el-checkbox>
                    <el-checkbox label="3">优质视频投流</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-card>
              <el-card class="mt-20">
                <div>
                  <div><span class="required"> * </span> 联系方式</div>
                  <div class="flex f-start-center">
                    <span class="ml-30 font-size-14"> 手机号 </span>
                    <el-input class="input-style ml-10" v-model="contact_info.phone">
                    </el-input>
                  </div>
                  <div class="flex mt-20 f-start-center">
                    <span class="ml-30 font-size-14"> 微信号 </span>
                    <el-input class="input-style ml-10" v-model="contact_info.wechat">
                    </el-input>
                  </div>
                </div>
              </el-card>
              <el-card class="mt-20">
                <div>
                  <div><span class="required"> * </span> 专属推荐商品</div>
                  <div class="mt-20">
                    <el-button type="primary" size="small" icon="el-icon-plus"
                      @click="showAddProduct = true">添加商品</el-button>
                    <span class="ml-10 font-size-12 color-898B8F">已添加{{ selectProductList.length }}/5</span>
                  </div>
                  <div>
                    <el-table :data="selectProductList" empty-text="暂无数据~">
                      <el-table-column label="商品信息">
                        <template slot-scope="{ row }">
                          <div class="flex f-start-center">
                            <img style="width: 32px; height: 32px" :src="row.cover" alt="" />
                            <div class="f--1 font-size-12 ml-10">
                              <el-tooltip class="item" effect="dark" :content="row.title" placement="top">
                                <div class="ellipsis-1" style="max-width: 265px">
                                  {{ row.title }}
                                </div>
                              </el-tooltip>

                              <div class="color-898B8F">
                                <span>售价：¥{{ String(row.price / 100) }}</span>
                                <span class="ml-10">全部达人佣金：{{ row.cos_ratio }}%</span>
                              </div>
                            </div>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column label="免审申样" width="200">
                        <template slot-scope="{ row }">
                          <el-switch v-model="row.author_sample_status" active-text="开" :active-value="3"
                            :inactive-value="1" inactive-text="关">
                          </el-switch>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="100">
                        <template slot-scope="{ row }">
                          <el-button type="text" @click="delProductData(row)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
                <div class="flex f-end-center mt-20 pr-20 mb-20">
                  <el-button type="primary" @click="sendMsg" icon="el-icon-s-promotion">
                    确认发送
                  </el-button>
                  <el-button @click="$emit('update:isDrawer', false)">
                    取消
                  </el-button>
                </div>
              </el-card>
            </div>
            <div class="pl-20 mt-10 mr-10">
              <el-card class="mt-60">
                <div class="font-size-12 font-color-2">效果展示</div>
                <img style="width: 286px; height: 620px" class="mt-10"
                  src="@/assets/images/structure_mesage_example.png" alt="" />
              </el-card>
            </div>
          </div>
        </template>
        <template v-if="stepsVal == 3">
          <el-card class="mt-20" v-if="successNum">
            <div slot="header" class="clearfix">
              <el-tag type="success">邀约成功: {{ successNum }}个达人</el-tag>
            </div>
            <div class="flex f-wrap" v-if="successNum">
              <div v-for="(item, index) in InvitationStataList.success" :key="index"
                class="flex f-start-center mb-20 w__25">
                <img :src="item.avatar" alt="" class="cursor-pointer" @click="openPage(item.avatar)"
                  style="width: 50px; height: 50px; border-radius: 50%" />

                <el-tooltip class="item" effect="dark" :content="item.nickname" placement="top-start">
                  <span class="font-size-16 ml-10 ellipsis-1" style="max-width: 220px">{{ item.nickname }}
                  </span>
                </el-tooltip>
                <span class="font-size-16 ml-10">
                  <span class="cursor-pointer font-size-14" @click="goChat(item)" style="color: #409eff">
                    前往聊天
                  </span>
                </span>
              </div>
            </div>
          </el-card>
          <el-card class="mt-20" v-if="failedNum">
            <div slot="header" class="clearfix">
              <el-tag type="danger">邀约失败：{{ failedNum }} 个达人</el-tag>
            </div>
            <div class="flex f-wrap">
              <div v-for="(item, index) in InvitationStataList.fail" :key="index"
                class="flex f-start-center mb-20 w__25">
                <img :src="item.msg_info.author_info.author_base.avatar" alt=""
                  style="width: 50px; height: 50px; border-radius: 50%" />

                <el-tooltip class="item" effect="dark" :content="item.hover" placement="top-start">
                  <span class="font-size-16 ml-10 ellipsis-1" style="max-width: 220px">
                    {{ item.msg_info.author_info.author_base.nickname }}
                  </span>
                </el-tooltip>
              </div>
            </div>
          </el-card>
          <div class="flex f--center mt-20">
            <el-button type="primary" @click="continueInviting">
              继续邀约
            </el-button>
          </div>
        </template>
      </div>
    </el-drawer>
    <addProductDialog :selectProductList="selectProductList" :showAddProduct.sync="showAddProduct" v-if="showAddProduct"
      @getUserAddProductData="getUserAddProductData" />
  </div>
</template>

<script>
import addProductDialog from "./addProduct.vue";
import { personMsg } from "@/api/invitation";
import crossClass from "@/utils/cross-domain.js";
export default {
  props: ["isDrawer", "tableData"],
  components: {
    addProductDialog,
  },
  data() {
    return {
      drawer: false,
      direction: "rtl",
      accordData: [],
      stepsVal: 1,
      isMultipleChoice: false,
      showAddProduct: false,
      contact_info: {
        content: "",
        phone: "",
        wechat: "",
      },
      rights: [],
      selectedCommodityTable: [],
      selectProductList: [],
      checkList: [],
      InvitationStataList: {
        success: [],
        fail: [],
      },
      isTips: false,
      fasonRecaver: false,
      successNum: 0,
      failedNum: 0,
      pageObj: {
        currentPage: 1,
        pageSize: 10,
      },
    };
  },
  mounted() {
    try {
      this.accordData = [...this.tableData].filter((item) => {
        return item.author_connection.im_status == 1;
      });
      this.viewViewport();
    } catch (error) {
      console.log(error);
    }
    this.initData();
  },
  methods: {
    handleCurrentChange(val) {
      this.pageObj.currentPage = val;
      this.scrollTop();
      // this.getIntelligentListFunc()
    },
    jumpPage(url) {
      window.open(url);
    },
    viewViewport() {
      this.$nextTick(() => {
        const box = this.$refs.box;
        if (
          box.scrollHeight > box.clientHeight ||
          box.offsetHeight > box.clientHeight
        ) {
          this.isTips = true;
          setTimeout(() => {
            this.isTips = false;
          }, 3000);
        }
      });
    },
    jumpHomepage(item) {
      function splitJoint(obj) {
        let arr = [];
        for (let key in obj) {
          arr.push(key + "=" + obj[key]);
        }
        return arr.length > 0 ? "?" + arr.join("&") : "";
      }
      let { uid } = item;
      let params = {
        enter_from: "1",
        previous_page_name: "3,5",
        previous_page_type: "4,100",
        log_id: "20240802180735D2CC7FEA944F8218FD25",
        search_id: "",
        btm_ppre: "a0.b0.c0.d0",
        btm_pre: "a52248.b31023.c473806.d0",
        btm_show_id: "9f4ceca0-99ae-4fa5-bef7-b23ca4152fa8",
        uid,
      };
      let url =
        "https://buyin.jinritemai.com/dashboard/servicehall/daren-profile" +
        splitJoint(params);
      window.open(url);
    },
    continueInviting() {
      this.$emit("update:isDrawer", false);
      setTimeout(() => {
        this.$parent.$children[1] && this.$parent.$children[1].showDrawer();
      }, 500);
    },
    async goChat(item) {
      console.log("item", item.uid);

      // console.log('row', row)
      const crossInstance = new crossClass();

      let checkUrlOpen = await crossInstance.checkUrlOpen([
        "https://buyin.jinritemai.com/dashboard", //达人广场
        "https://fxg.jinritemai.com/ffa", // 抖店后台
      ]);
      let { code, data } = checkUrlOpen;
      if (code == 200) {
        let douDian = data.find((item) => {
          return (
            item.url == "https://fxg.jinritemai.com/ffa" && item.status == true
          );
        });
        let darenSquare = data.find((item) => {
          return (
            item.url == "https://buyin.jinritemai.com/dashboard" &&
            item.status == true
          );
        });
        if (!douDian) {
          let str = "使用该功能需要打开并登录抖店";
          let url = "https://fxg.jinritemai.com/login/common?from=buyin";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }
        if (!darenSquare) {
          let str = "使用该功能需要打开并登录达人广场";
          let url =
            "https://buyin.jinritemai.com/dashboard/servicehall/daren-square?previous_page_name=3&previous_page_type=4";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }
        crossInstance
          .sendMessageForPageFunc({
            id: darenSquare.id,
            script: `fetch('https://buyin.jinritemai.com/connection/pc/im/account?account_type=1&account_app_id=1128&account_id=${item.uid}',{
                            method: 'GET',
                            })
                            .then((res) => {
                            return res.json()
                            })
                            .then((res) => {
                            window.postMessage({
                                    type_urs: 'wkyy-wtbg',
                                    data: res,
                                    type_page: 'pageMeat',
                                    method: 'send_message_for_page'
                                })
                            })
                        `,
          })
          .then((res) => {
            console.log("res", res);
            const { code, data } = res;
            if (code == 200) {
              if (data.code == 0) {
                const getdfijer = data.data;
                let { buyin_account_id, im_id } = getdfijer;
                function splitJoint(obj) {
                  let arr = [];
                  for (let key in obj) {
                    arr.push(key + "=" + obj[key]);
                  }
                  return arr.length > 0 ? "?" + arr.join("&") : "";
                }
                let urlss =
                  "https://buyin.jinritemai.com/mpa/pigeonIM" +
                  splitJoint({
                    friendId: im_id,
                    buyinId: buyin_account_id,
                    pick_first_source: "达人直播主页",
                    previous_page_name: 3,
                    previous_page_type: 4,
                  });
                window.open(urlss);
              }
            }
          })
          .catch((err) => {
            window.open(url);
          });
      }
      // let {
      //     target_account: { buyin_account_id, im_id }
      // } = item
      // function splitJoint (obj) {
      //     let arr = []
      //     for (let key in obj) {
      //         arr.push(key + '=' + obj[key])
      //     }
      //     return arr.length > 0 ? '?' + arr.join('&') : ''
      // }
      // let url =
      //     'https://buyin.jinritemai.com/mpa/pigeonIM' +
      //     splitJoint({
      //         friendId: im_id,
      //         buyinId: buyin_account_id,
      //         pick_first_source: '达人直播主页',
      //         previous_page_name: 3,
      //         previous_page_type: 4
      //     })
      // window.open(url)
    },
    openPage(val) {
      window.open(val);
    },
    async initData() {
      const crossInstance = new crossClass();

      let checkUrlOpen = await crossInstance.checkUrlOpen([
        "https://buyin.jinritemai.com/dashboard", //达人广场
        "https://fxg.jinritemai.com/ffa", // 抖店后台
      ]);
      let { code, data } = checkUrlOpen;
      if (code == 200) {
        let douDian = data.find((item) => {
          return (
            item.url == "https://fxg.jinritemai.com/ffa" && item.status == true
          );
        });
        let darenSquare = data.find((item) => {
          return (
            item.url == "https://buyin.jinritemai.com/dashboard" &&
            item.status == true
          );
        });
        if (!douDian) {
          let str = "使用该功能需要打开并登录抖店";
          let url = "https://fxg.jinritemai.com/login/common?from=buyin";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }
        if (!darenSquare) {
          let str = "使用该功能需要打开并登录达人广场";
          let url =
            "https://buyin.jinritemai.com/dashboard/servicehall/daren-square?previous_page_name=3&previous_page_type=4";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }

        crossInstance
          .sendMessageForPageFunc({
            id: darenSquare.id,
            script: `fetch('https://buyin.jinritemai.com/connection/pc/im/card/sender/msg?card_type=0',{
                            method: 'GET',
                            })
                            .then((res) => {
                            return res.json()
                            })
                            .then((res) => {
                            window.postMessage({
                                    type_urs: 'wkyy-wtbg',
                                    data: res,
                                    type_page: 'pageMeat',
                                    method: 'send_message_for_page'
                                })
                            })
                        `,
          })
          .then((res) => {
            console.log(res, "11111");
            let { code, data } = res;
            if (
              code == 200 &&
              data.code == -1 &&
              data.msg == "您已被关闭推广，无法使用平台功能"
            ) {
              this.$message.error(
                "您暂时还不满足邀约达人的条件，请前往官网开通该权限"
              );
              return;
            }
            if (code == 200 && data.code == 0) {
              let { contact_info, invite_card_info } = data.data;
              this.contact_info = {
                content: invite_card_info.content,
                phone: contact_info.phone,
                wechat: contact_info.wechat,
              };
              this.rights = invite_card_info.rights_info.map((item) => {
                return String(item.right);
              });
              this.selectProductList =
                data.data.invite_card_info.product_infos.map((item, index) => {
                  return {
                    title: item.base_info.title,
                    cover: item.base_info.cover,
                    product_id: item.product_id,
                    promotion_id: item.promotion_id,
                    author_sample_status:
                      data.data.invite_card_info.buy_sample_info.find(
                        (it) => it.product_id == item.product_id
                      ).author_sample_status,
                    price: item.price_info.price,
                    cos_ratio: item.cos_info.cos_ratio,
                  };
                });
            }
            crossInstance.closeListen();
          })
          .catch((err) => {
            crossInstance.closeListen();
          });
        setTimeout(() => {
          crossInstance.closeListen();
        }, 2000);
      }

      //   personMsg({
      //     card_type: 0,
      //     verifyFp: 'verify_lyf5ie1a_PDOUr7Op_Pdw5_4lJ2_92eo_xW2e350m34Zc',
      //     fp: 'verify_lyf5ie1a_PDOUr7Op_Pdw5_4lJ2_92eo_xW2e350m34Zc',
      //     msToken:
      //       'h90D3YEFGE2QmULBWHjOj5AIsAGv3F6wx6v8qdAQ-2yHyxk-5WtKMRdkm-hlUDaRFC8kAXkpcxhO7XvFcvkZbLBP6z-2H9ZYA-J5dFbPWcFxXdByUGdM3w==',
      //     a_bogus:
      //       'xyWhQRzgdDdiff8D56ALfY3qfHH3Y0xo0SVkMDgbqn3/8g39HMPF9exEXmGvC2bjNs/DIebjy4hbY3/grQd701wR9SfKWoO/-hbDeM3kso4j53iruyRkrzDF-vGWS-BBRk-lrOX0w7lHFbumWnA75XqvPjoja3LkFk6FOoQO'
      //   })
      // .then((res) => {
      //   let { data, code } = res
      //   if (code == 0) {
      //     let { contact_info, invite_card_info } = data
      //     this.contact_info = {
      //       content: invite_card_info.content,
      //       phone: contact_info.phone,
      //       wechat: contact_info.wechat
      //     }
      //     this.rights = invite_card_info.rights_info.map((item) => {
      //       return String(item.right)
      //     })
      //     this.selectProductList = data.invite_card_info.product_infos.map(
      //       (item, index) => {
      //         return {
      //           title: item.base_info.title,
      //           cover: item.base_info.cover,
      //           product_id: item.product_id,
      //           promotion_id: item.promotion_id,
      //           author_sample_status:
      //             data.invite_card_info.buy_sample_info.find(
      //               (it) => it.product_id == item.product_id
      //             ).author_sample_status,
      //           price: item.price_info.price,
      //           cos_ratio: item.cos_info.cos_ratio
      //         }
      //       }
      //     )
      //   }
      //     })
      //     .catch((err) => {})
    },
    sendMsg() {
      const phoneRegex = /^1[3456789]\d{9}$/;
      // const isPurchase = localStorage.getItem('isPurchase')
      // if (isPurchase && isPurchase == '0') {
      //     this.$confirm('未订购抖羚羊插件，无法正常使用', '提示', {
      //         confirmButtonText: '前往订购',
      //         cancelButtonText: '取消',
      //         type: 'warning'
      //     })
      //         .then((res) => {
      //             window.open(localStorage.getItem('orderingAddress'))
      //         })
      //         .catch((err) => { })
      //     return
      // }
      if (this.contact_info.content == "") {
        this.$message.warning("请填写邀约信息", 5000);
        return;
      } else if (this.contact_info.phone == "") {
        this.$message.warning("请填写手机号", 5000);
        return;
      }
      // else if (this.contact_info.wechat == "") {
      //   this.$message.warning("请填写微信号", 5000);
      //   return;
      // }
      else if (!phoneRegex.test(this.contact_info.phone)) {
        this.$message.warning("请填写正确的手机号", 5000);
        return;
      } else if (this.selectProductList.length == 0) {
        this.$message.warning("请添加专属推荐商品", 5000);
        return;
      }
      let collectData = () => {
        let params = {};
        let rights = this.rights.map((item) => {
          return {
            right: Number(item),
          };
        });
        console.log("this.contact_info.content", this.contact_info.content);
        let invite_card = {
          // content: this.contact_info.content,
          content: this.contact_info.content.replace(/\n/g, "  "),

          rights,
          product_ids: this.selectProductList.map((it) => {
            return it.product_id;
          }),
          product_setting: this.selectProductList.map((it) => {
            return {
              product_id: it.product_id,
              author_sample_status: it.author_sample_status,
            };
          }),
        };
        params = {
          contact_info: {
            phone: this.contact_info.phone,
            wechat: this.contact_info.wechat,
          },
          invite_card,
        };
        return params;
      };

      let allParams = this.accordData.map((item) => {
        let {
          author_base: { uid },
        } = item;
        return {
          account_id: uid,
          account_type: 1,
          ...collectData(),
        };
      });
      // console.log('allParams00..33221', allParams)
      const getCOnters = {
        message_content: {
          contact_info: allParams[0].contact_info,
          invite_card: allParams[0].invite_card,
        },
      };
      const allPutDataer = [];
      while (allParams.length > 0) {
        let params = allParams.splice(0, 40);
        const djyetyr = {
          receiver_messages: params.map((item) => {
            return {
              receiver: {
                account_id: item.account_id,
                account_type: 24,
              },
            };
          }),
          ...getCOnters,
          source: 5,
        };
        allPutDataer.push(djyetyr);
      }
      // console.log("djyetyrdjyetyrdjyetyrdjyetyr", allPutDataer);

      this.batchInvitation(allPutDataer);
    },
    async batchInvitation(allParams) {
      allParams = allParams.map((item) => {
        return `fetch(
                    'https://buyin.jinritemai.com/connection/pc/im/shangda/msgs/send',
                    {
                        method: 'POST',
                        headers: {
                        'Content-Type': 'application/json'
                        },
                         body:'${JSON.stringify({ ...item })}',
                    }
                    ).then((res)=>{
                         return res.json()
                    })
                    `;
      });
      console.log(allParams);
      let script = `Promise.all([${allParams}]).then((res) => {
                window.postMessage({
                type_urs: 'wkyy-wtbg',
                data: res,
                type_page: 'pageMeat',
                method: 'send_message_for_page'
                })
            })`;
      const crossInstance = new crossClass();
      let checkUrlOpen = await crossInstance.checkUrlOpen([
        "https://buyin.jinritemai.com/dashboard",
      ]);
      if (checkUrlOpen.code == 200) {
        let find = checkUrlOpen.data.find((item) => {
          return (
            item.url == "https://buyin.jinritemai.com/dashboard" &&
            item.status == true
          );
        });

        if (!find) {
          this.$confirm("使用该功能需要打开并登录达人广场", "提示", {
            confirmButtonText: "前往打开",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then((res) => {
              window.open(
                "https://buyin.jinritemai.com/dashboard/servicehall/daren-square"
              );
            })
            .catch((err) => { });
          return;
        }

        console.log("checkUrlOpen", checkUrlOpen, find, script);
        this.fasonRecaver = true;
        let sendMessageForPageData = await crossInstance.sendMessageForPageFunc(
          {
            id: find.id,
            script,
          }
        );
        this.stepsVal = 3;
        this.fasonRecaver = false;
        if (sendMessageForPageData) {
          try {
            console.log(sendMessageForPageData, "sendMessageForPageData");
            let { data, code } = sendMessageForPageData;

            if (code == 200) {
              let successList = data
                .filter((item) => item.code == 0)
                .map((item) => {
                  return {
                    ...item.data,
                  };
                });

              console.log(successList, "successList");
              console.log("allParams", this.accordData);
              // this.InvitationStataList.success = successList
              successList.forEach((item) => {
                this.successNum = this.successNum + item.biz_success_count;
                this.failedNum = this.failedNum + item.biz_failed_count;
                if (item.biz_failed_list && item.biz_failed_list.length > 0) {
                  item.biz_failed_list.forEach((item2) => {
                    this.InvitationStataList.fail.push(item2);
                  });
                }
              });
              this.accordData.forEach((itemiuter) => {
                const getUids = itemiuter.author_base.uid;
                console.log("getUids", getUids);
                const getFailDataIsInfo = this.InvitationStataList.fail.find(
                  (iyter) => {
                    return iyter.msg_info.receiver.account_id === getUids;
                  }
                );
                console.log("以及在失败列表里面的", getFailDataIsInfo);
                if (!getFailDataIsInfo) {
                  // console.log('成功的', itemiuter)
                  this.InvitationStataList.success.push(itemiuter.author_base);
                  // if( this.InvitationStataList.success.every(item => item.author_base.uid !== getUids) ) {
                  //     this.InvitationStataList.success.push(itemiuter.author_base)
                  // }
                }
              });
              console.log(this.InvitationStataList);
              // let successNameList = successList.map((item) => {
              //     return item.biz_success_count
              // })

              // if ((successNameList.length == this.accordData.length) == false) {
              //     let failNameList = this.accordData.filter((item) => {
              //         return successNameList.length == 0
              //             ? true
              //             : !successNameList.includes(item.author_base.nickname)
              //     })
              //     this.InvitationStataList.fail = JSON.parse(
              //         JSON.stringify(failNameList)
              //     )
              // }
              if (this.$parent.$children[1]) {
                this.$parent.$children[1].scrollTop();
                this.$parent.$children[1].refoLisuehr();
              }
            }
          } catch (error) {
            // console.log(error, '11111')
          }
        }
        crossInstance.closeListen();
      }
    },
    delProductData(item) {
      let { product_id, promotion_id } = item;
      this.selectProductList = this.selectProductList.filter((item) => {
        return (
          item.product_id != product_id && item.promotion_id != promotion_id
        );
      });
    },
    getUserAddProductData(data) {
      this.selectProductList = data.map((item) => {
        return {
          ...item,
          author_sample_status: 1,
        };
      });
    },
    cancelAllInvitation() {
      if (!this.isMultipleChoice) {
        this.isMultipleChoice = true;
        return;
      } else if (this.checkList.length == 0) {
        this.isMultipleChoice = false;
        return;
      }
      this.$confirm("确认取消邀约这批达人吗？")
        .then((_) => {
          this.accordData = this.accordData.filter((item) => {
            let {
              author_base: { uid },
            } = item;
            return !this.checkList.includes(uid);
          });
          this.isMultipleChoice = false;
          this.checkList = [];
        })
        .catch((_) => { });
    },
    cancelInvitation(val) {
      this.$confirm("确认取消邀约该达人吗？")
        .then((_) => {
          this.accordData = this.accordData.filter((item) => {
            let {
              author_base: { uid, nickname },
            } = item;
            return (
              val.author_base.uid != uid && val.author_base.nickname != nickname
            );
          });
        })
        .catch((_) => { });
    },
    handleClose() {
      this.$confirm("确认关闭吗？")
        .then((_) => {
          this.$emit("update:isDrawer", false);
        })
        .catch((_) => { });
    },
    stateReturnVal(status, value, type) {
      let [a, b] = value;
      if (status == 0) {
        let str;
        if (a == b) {
          str = a;
        } else {
          str = `${a}-${b}`;
        }
        if (type == "money") {
          str = "¥" + str;
        }
        return str;
      } else if (status == 1) {
        return "达人未授权";
      } else if (status == 2) {
        return "-";
      }
    },
    commonNumFilter(num) {
      if (num == 0) {
        return num;
      } else if (Number(num) < 10000) {
        return num;
      } else {
        return (Number(num) / 10000).toFixed(2) + "万";
      }
    },
  },
  computed: {
    accordDatauteyr() {
      return this.accordData.slice(
        (this.pageObj.currentPage - 1) * this.pageObj.pageSize,
        this.pageObj.currentPage * this.pageObj.pageSize
      );
    },
  },
};
</script>

<style scoped>
/deep/ .el-drawer__body {
  overflow-y: auto;
}

.table-box .prompt {
  width: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -250px;
  background: hsl(0, 3%, 39%);
  border-radius: 10px;
  color: #ffff;
}

.table-box-prompt-img {
  width: 200px;
  height: 200px;
}

.input-style {
  width: 300px;
}

.required {
  color: red;
}

.img-style {
  width: 36px;
  height: 36px;
  border-radius: 50%;
}

.tag {
  background-color: transparent;
  color: rgb(105, 113, 140);
  border: 1px solid rgb(232, 232, 233);
  line-height: 14px;
  padding: 3px;
}

.primary-tag {
  background-color: transparent;
  color: rgb(25, 102, 255);
  border: 1px solid rgba(25, 102, 255, 0.12);
  line-height: 14px;
  padding: 3px;
}
</style>
